package com.windmill.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.windmill.bean.Card;
import com.windmill.bean.ChangeCard;
import com.windmill.bean.GroupUser;
import com.windmill.bean.ThemeCard;
import com.windmill.cmd.CommandConstants;
import com.windmill.test.CardInfoV3;
import com.windmill.util.CardUtil;
import com.windmill.util.TextUtils;

public class DataStore implements Serializable{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(DataStore.class);
	private CardStore cardStore;
	private Map<Long,GroupUser> groupUserMap;//qq
	private List<ChangeCard> changeCardList;
	private List<String> welcome;
	private String gUserFile;
	private String cCardFile;
	public DataStore(CardStore cardStore){
		this.cardStore = cardStore;
		this.groupUserMap = new HashMap<Long,GroupUser>();		
		this.changeCardList = new ArrayList<ChangeCard>();
		this.setWelcome(new ArrayList<String>());
	}
	public void init(String gUserFile, String cCardFile) {
		this.gUserFile = gUserFile;
		this.cCardFile = cCardFile;
		loadGroupUserData(gUserFile);
		loadChangeCardData(cCardFile);
		loadWelcome("welcome.txt");
		storeDataStore(10);//开启时间线程每 N 分钟保存数据
	}

	private void storeDataStore(int min) {
		final Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				storeDataStore();
			}
		}, min*600000,min*100000);
		
	}
	public void storeDataStore(){
		storeGroupUserData(gUserFile);
		storeChangeCardData(cCardFile);
		LOG.debug("dataStore 保存数据.");
	}
	private void storeChangeCardData(String dataFile) {
		File dir = new File(System.getProperty("user.dir")+"/data");
		if(!dir.exists())dir.mkdirs();
		List<String> list = new ArrayList<String>();
		for(ChangeCard cCard:changeCardList){
			if(cCard.getCards().size()==0)continue;
			StringBuffer sb = new StringBuffer(cCard.getLinkQQ()+";");//目标QQ
			for(int i=0;i<cCard.getChangeThemes().size();i++){     	  //theme
				ThemeCard t = cCard.getChangeThemes().get(i);
				if(i!=cCard.getChangeThemes().size()-1){
					sb.append(t.getId()+",");
				}else{
					sb.append(t.getId());
				}				
			}
			sb.append(";");
			for(int i=0;i<cCard.getCards().size();i++){					//cards
				Card c = cCard.getCards().get(i);
				if(i!=cCard.getCards().size()-1){
					sb.append(c.getId()+",");
				}else{
					sb.append(c.getId()+";");
				}				
			}
			sb.append(cCard.getSaveQQ());							//saveqq
			list.add(sb.toString());
		}
		TextUtils.writeLine(list, dir.getAbsolutePath()+"/"+dataFile);
	}
	public void loadChangeCardData(String dataFile){
		String path = System.getProperty("user.dir")+"/data/"+dataFile;
		if(new File(path).exists()){
			List<String> list = TextUtils.readLine(path);
			for(int i=0;i<list.size();i++){
				String[] params = list.get(i).split(";");
				if(params.length!=4)continue;
				ChangeCard cCard = new ChangeCard();
				cCard.setLinkQQ(Long.valueOf(params[0]));//目标QQ
				if(params[1]!=null&&!"".equals(params[1])){//theme
					String[] tids = params[1].split(",");
					for(String tid:tids){
						cCard.getChangeThemes().add(cardStore.getThemeById(Integer.valueOf(tid)));
					}
				}
				if(params[2]!=null&&!"".equals(params[2])){//theme
					String[] cids = params[2].split(",");
					for(String cid:cids){
						cCard.getCards().add(cardStore.getCardById(Integer.valueOf(cid)));
					}
				}
				cCard.setSaveQQ(Long.valueOf(params[3]));
				this.changeCardList.add(cCard);
			}
		}		
	}
	public void storeGroupUserData(String dataFile) {
		File dir = new File(System.getProperty("user.dir")+"/data");
		if(!dir.exists())dir.mkdirs();
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(dir,dataFile)));
			oos.writeObject(this.groupUserMap);
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	@SuppressWarnings("unchecked")
	private void loadGroupUserData(String dataFile) {
		String path = System.getProperty("user.dir")+"/data/"+dataFile;
		if(new File(path).exists()){
			ObjectInputStream ois = null;
			try {
				ois = new ObjectInputStream(new FileInputStream(path));
				Map<Long,GroupUser> data =  (Map<Long,GroupUser>) ois.readObject();
				this.groupUserMap = data;
			} catch (Exception e) {				
			}finally{
				try {ois.close();} catch (IOException e) {e.printStackTrace();}
			}
		}	
	}
	private void loadWelcome(String file) {
		String path = System.getProperty("user.dir")+"/data/"+file;
		if(new File(path).exists()){
			this.welcome = TextUtils.readLine(path);
			for(String key:CommandConstants.instruction.keySet()){
				welcome.add(CommandConstants.instruction.get(key));
			}
		}
	}
	public Map<Long, GroupUser> getGroupUserMap() {
		return groupUserMap;
	}
	public void setGroupUserMap(Map<Long, GroupUser> groupUserMap) {
		this.groupUserMap = groupUserMap;
	}
	public List<ChangeCard> getChangeCardList() {
		return changeCardList;
	}
	public void setChangeCardList(List<ChangeCard> changeCardList) {
		this.changeCardList = changeCardList;
	}
	public void addGroupUser(GroupUser guser){
		this.groupUserMap.put(guser.getQq(), guser);
	}
	public GroupUser getGoupUserByQQ(long qq){
		return this.groupUserMap.get(qq);
	}
	public String getWelcome() {
		if(welcome.size()>0){
			Random r = new Random();
			int index = r.nextInt(welcome.size());
			return welcome.get(index);
		}
		return "";
	}
	public void setWelcome(List<String> welcome) {
		this.welcome = welcome;
	}
	public boolean isLinkQQExist(long linkQQ) {
		for(ChangeCard cc:changeCardList){
			if(cc.getLinkQQ()==linkQQ){
				return true;
			}
		}
		return false;
	}
	public void addOrUpdateChangeCard(ChangeCard cCard){
		for(ChangeCard cc:changeCardList){
			if(cc.getLinkQQ()==cCard.getLinkQQ()){
				changeCardList.remove(cc);
				cCard.setSaveQQ(cc.getSaveQQ());
				break;
			}
		}
		if(cCard.getCards().size()>0)
			changeCardList.add(cCard);
	}
	public List<ChangeCard> findChangeCardByCardName(String cardName, String themeName){
		List<ChangeCard> list = new ArrayList<ChangeCard>();
		for(ChangeCard cCard:changeCardList){
			for(Card card:cCard.getCards()){
				if(card.getName().equals(cardName)&&("".equals(themeName)||card.getTheme().getName().equals(themeName))){
					list.add(cCard);
					break;
				}
			}
		}
		return list;
	}
	public List<Card> findChangeCardByThemeName(String themeName){
		List<Card> list = new ArrayList<Card>();
		for(ChangeCard cCard:changeCardList){
			for(Card card:cCard.getCards()){
				if(card.getTheme().getName().equals(themeName)){
					list.add(card);
				}
			}
		}
		return list;
	}
	public String getChangeCardNamesByThemeName(String ThemeName){
		StringBuffer sb = new StringBuffer();
		for(ChangeCard cCard:changeCardList){
			for(Card card:cCard.getCards()){
				if(card.getTheme().getName().equals(ThemeName)&&!sb.toString().contains(card.getName())){
					sb.append(card.getName()+";");
				}
			}
		}
		return sb.toString();
	}
	public static DataStore filterChangeCard() throws FileNotFoundException{
		//new FileInputStream("D:\\Workspaces\\MagicWindmill\\data\\cardinfo.js")
		CardInfoV3 v3 = new CardInfoV3();
		DataStore data = new DataStore(v3.getCardStore());
		data.init("GroupUserData.fc", "ChangeCardData.txt");
		System.out.println(data.getChangeCardList().size());
		System.out.println(data.getGroupUserMap().size());

		
		List<ChangeCard> changeCardList = new ArrayList<ChangeCard>();
		for(ChangeCard cCard:data.getChangeCardList()){
			List<Card> cards = CardUtil.filterUsefulCard(cCard.getCards(),cCard.getChangeThemes());
			if(cards.size()==0){
				System.err.println(cCard.getChangeThemes());
				System.err.println("移除："+cCard.getLinkQQ()+" "+cCard.getCardsName());
			}else{
				cCard.setCards(cards);	
				changeCardList.add(cCard);
			}
		}		
		data.setChangeCardList(changeCardList);
		return data;
		
	}
	public static void main(String[] args) throws Exception {
		DataStore data = filterChangeCard();
		System.out.println(data.getChangeCardList().size());
		System.out.println(data.getGroupUserMap().size());
//		data.storeGroupUserData("GroupUserData.fc.new");
//		data.storeChangeCardData("ChangeCardData.txt.new");
	}
	
}
